import subprocess
import re
import os
import shutil

# import ..global_vars.globalvars
from ..global_vars import globalvars


def func(*arg):
    globalvars.progress = []

    command = "./bs_code/gen"
    args = ["filtered", "0", "512"]
    args[0] = "filtered" if arg[1] else "unfiltered"
    args[1] = str(arg[2])
    args[2] = str(arg[0])

    process = subprocess.Popen(
        [command] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
    )

    try:
        while globalvars.message == "start":
            next_line = process.stdout.readline()

            if next_line == "" and process.poll() is not None:
                break

            if "d =" in next_line:
                globalvars.progress.append("error")
                globalvars.message = "stop"
                break

            if "Collected" in next_line:
                str_list = re.findall(r"\d+", next_line)
                int_list = [int(s) for s in str_list]
                globalvars.progress.append(int_list[0])

        if globalvars.message != "start":
            process.terminate()
            try:
                process.wait(timeout=5)  # 等待子进程终止，最多等待5秒
            except subprocess.TimeoutExpired:
                process.kill()  # 如果子进程没有在5秒内终止，强制终止
                process.wait()  # 确保子进程已经被终止

    except Exception as e:
        print(f"出现异常: {e}")
        process.terminate()
        try:
            process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            process.kill()
            process.wait()

    finally:
        globalvars.progress.append("complete")
        globalvars.message = "stop"

        error_output = process.stderr.read()
        if error_output:
            print("错误输出:")
            print(error_output)

    return 0


def func2(*arg):
    # file_name = 'cutfilter_Kyber768Simplified_seed7175_lvu.txt'
    # index_l = 2
    # index_r = 4
    file_name = arg[0]
    index_l = arg[1]
    index_r = arg[2]

    # current_path = os.getcwd()
    # print(current_path)
    # current_path = (
    #     current_path
    #     + "/bs_code/inequalities/"
    #     + ("filtered" if file_name[0] == "c" else "unfiltered")
    # )
    # print(current_path)

    # print(file_name[-7:-4])
    relative_path = "bs_code/inequalities/" + (
        "filtered/" if file_name[0] == "c" else "unfiltered/"
    )
    relative_path = relative_path + file_name
    print(relative_path)
    flag = 3
    if index_r == 0 and index_l == 0:
        flag = 1
    else:
        if file_name[-7:-4] == "lvu":
            flag = 2
    # 1：密钥 2：上下界 3：系数

    result = []
    with open(relative_path, "r") as file:
        # 逐行读取文件内容
        for line in file:
            if flag == 1:
                a = int(line)
                result.append(a)
            if flag == 2:
                a, b, c = line.split()
                a = int(a)
                b = int(b)
                c = int(c)
                result.append([a, c])
            if flag == 3:
                str_list = line.split()
                int_list = [int(s) for s in str_list]
                result.append(int_list)

    if flag == 1:
        globalvars.data = result
        # print(result)
    else:
        globalvars.data = result[index_l:index_r]
        # print(len(globalvars.data))
        # print(len(globalvars.data[0]))
        # print(result[index_l:index_r])
    globalvars.message = "stop"

    return 0
